package com.ddtech.platform;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.zeroturnaround.zip.ZipUtil;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.List;

public class Zipper {
	/**
	 * zip a folder into .zip
	 * 
	 * @param folder
	 * @throws IOException
	 */
	public static File pack(File folder, List<String> postfix) throws IOException {
		File td = createTempDirectory();
		FileUtils.copyDirectory(folder, td, new FileFilter(){

			@Override
			public boolean accept(File f) {
				if(f.isFile() && postfix!=null){
					if(!postfix.contains(FilenameUtils.getExtension(f.getName()))){
						return false;
					}
				}
				return true;
			}
			
		});
		File temptarget = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".zip");
		ZipUtil.pack(td, temptarget);
		
		try{
			FileUtils.deleteDirectory(td);
		}catch(Exception e){
			e.printStackTrace();
		}
		return temptarget;
	}

	public static File createTempDirectory() throws IOException {
		final File temp;

		temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

		if (!(temp.delete())) {
			throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
		}

		if (!(temp.mkdir())) {
			throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
		}

		return (temp);
	}
}
